package cn.wjh.business.service.impl;

import cn.wjh.business.domain.Competition;
import cn.wjh.business.domain.Works;
import cn.wjh.business.domain.WorksMark;
import cn.wjh.business.mapper.WorksMapper;
import cn.wjh.business.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 比赛作品Service业务层处理
 *
 * @author jiraWu
 * @date 2023-10-20
 */
@Service
public class WorksServiceImpl extends ServiceImpl<WorksMapper, Works> implements IWorksService {
	@Resource
	private WorksMapper worksMapper;
	@Resource
	private ICollectService collectService;

	@Resource
	private ICompetitionService competitionService;
	@Resource
	private ICompetitionSignService competitionSignService;
	@Resource
	private IWorksMarkService worksMarkService;

	/**
	 * 查询比赛作品
	 *
	 * @param worksId 比赛作品主键
	 * @return 比赛作品
	 */
	@Override
	public Works selectWorksByWorksId(Long worksId) {
		Works works = worksMapper.selectWorksByWorksId(worksId);
		works.setCollect(collectService.countByDataIdAndType(worksId, "works"));
		return works;
	}

	/**
	 * 查询比赛作品列表
	 *
	 * @param works 比赛作品
	 * @return 比赛作品
	 */
	@Override
	public List<Works> selectWorksList(Works works) {
		List<Works> worksList = worksMapper.selectWorksList(works);
		/*收藏数量*/
		worksList.forEach(w -> {
			w.setCollect(collectService.countByDataIdAndType(w.getWorksId(), "works"));
		});
		return worksList;
	}

	/**
	 * 新增比赛作品
	 *
	 * @param works 比赛作品
	 * @return 结果
	 */
	@Override
	public int insertWorks(Works works) {
		try {

			/*比赛不存在*/
			Long competitionId = works.getCompetitionId();//比赛Id
			Competition competition = competitionService.getById(competitionId);//比赛
			if (StringUtils.isNull(competition)) throw new ServiceException("当前比赛不存在,无法提交作品!");

			/*没有报名*/
			boolean sign = competitionSignService.isSign(competitionId);
			if (!sign) throw new ServiceException("您还未报名,请先报名再提交作品!");

			Date currentDate = DateUtils.getNowDate();
			Date signStartTime = competition.getSignStartTime();
			Date signEndTime = competition.getSignEndTime();
			Date endTime = competition.getEndTime();
			/*不在报名时间内
			 * currentDate > signStartTime && currentDate < signEndTime */
			boolean flag = currentDate.after(signStartTime) && currentDate.before(endTime);
			if (!flag) throw new ServiceException("不在比赛时间内,无法提交作品!", 601);

			/*管理员提交作品*/
			Long userId = SecurityUtils.getUserId();
			if (userId == 1) throw new ServiceException("尊敬的管理员,您无法提交作品!", 601);

			/*当前赛事评委*/
			List<Long> judgeIds = competition.getJudgeIds();
			if (!judgeIds.isEmpty() && judgeIds.contains(userId))
				throw new ServiceException("尊敬的赛事评委,您无法提交作品!", 601);

			/*正常提交作品*/
			works.setCreateTime(DateUtils.getNowDate());
			works.setCreateBy(SecurityUtils.getUsername());
			works.setUserId(userId);
			return worksMapper.insertWorks(works);
		} catch (DuplicateKeyException e) {
			throw new ServiceException("作品已提交,请勿重复提交!", 601);
		}
	}

	/**
	 * 修改比赛作品
	 *
	 * @param works 比赛作品
	 * @return 结果
	 */
	@Override
	public int updateWorks(Works works) {
		Works work = this.getById(works.getWorksId());
		if (StringUtils.isNull(work)) throw new ServiceException("作品不存在！", 400);
		/*审核通过*/
		if (work.getStatus().equals(1)) {
			throw new ServiceException("审核通过的作品无法修改", 400);
		}
		if (work.getStatus().equals(2)) {
			works.setReason("");//原因
			works.setStatus(0);//待审核
		}
		works.setUpdateTime(DateUtils.getNowDate());
		works.setUpdateBy(SecurityUtils.getUsername());
		return worksMapper.updateWorks(works);
	}

	/**
	 * 批量删除比赛作品
	 *
	 * @param worksIds 需要删除的比赛作品主键
	 * @return 结果
	 */
	@Override
	public int deleteWorksByWorksIds(Long[] worksIds) {
		return worksMapper.deleteWorksByWorksIds(worksIds);
	}

	/**
	 * 删除比赛作品信息
	 *
	 * @param worksId 比赛作品主键
	 * @return 结果
	 */
	@Override
	public int deleteWorksByWorksId(Long worksId) {
		return worksMapper.deleteWorksByWorksId(worksId);
	}

	/*是否发布作品*/
	@Override
	public boolean isPublish(Long competitionId) {
		Long userId = SecurityUtils.getUserId();
		Works works = getOneByUserIdAndCompetition(userId, competitionId);
		return StringUtils.isNotNull(works);
	}

	/**
	 * 获取我的作品
	 *
	 * @return
	 */
	@Override
	public List<Works> myWorks(Works works) {
		works.setUserId(SecurityUtils.getUserId());
		return this.selectWorksList(works);
	}

	/*根据比赛Id和用户Id获取作品详细*/
	@Override
	public Works getInfoByCompetitionIdAndUserId(Long userId, Long competitionId) {
		return getOneByUserIdAndCompetition(userId, competitionId);
	}

	/**
	 * 获取作品排名数据
	 *
	 * @param works
	 * @return
	 */
	@Override
	public List<Works> rank(Works works) {
		return worksMapper.rank(works);
	}

	/**
	 * 判断作品点评状态，返回作品集合
	 *
	 * @param
	 * @return
	 */
	@Override
	public List<Works> judgement(Works works) {
		//遍历比赛
		List<Competition> competitions = competitionService.selectCompetitionList(new Competition());
		List<Works> allWorksList = new ArrayList<>();
		competitions.forEach(competition -> {
			List<Long> judgeIds = competition.getJudgeIds();
			Long userId = SecurityUtils.getUserId();
			//判断是否为该比赛评委
			if (!judgeIds.contains(userId)) return;
			//查询比赛下的作品
			works.setCompetitionId(competition.getCompetitionId());
			works.setStatus(1);//审核通过
			List<Works> worksList = worksMapper.selectWorksList(works);
			//是否评价
			worksList.forEach(works1 -> {
				WorksMark worksMark = worksMarkService.getInfoByWorksIdAndUserId(works1.getWorksId(), userId);
				works1.setJudgement(worksMark != null);
				works1.setJudgeIds(competition.getJudgeIds());
			});
			allWorksList.addAll(worksList);
		});
		return allWorksList.stream().filter(item->item.getJudgement().equals(works.getJudgement())).collect(Collectors.toList());
	}

	/*根据用户Id和比赛Id获取作品详细*/
	public Works getOneByUserIdAndCompetition(Long userId, Long competitionId) {
		LambdaQueryWrapper<Works> selectWrapper = new QueryWrapper<Works>().lambda()
				.eq(Works::getCompetitionId, competitionId)
				.eq(Works::getUserId, userId);
		return this.getOne(selectWrapper);
	}
}
